﻿/*----------------------------------------------------------------
// Copyright (C) 2013 上海汽车集团股份有限公司
// 版权所有。
//
// 文件名：ImportExport.js
// 文件功能描述：导入导出文件
//              文件依赖： 
//                       jquery-1.8.0.min.js、
//                       Window.js 、
//                       Common.js
//
//
// 创建标识：  何权洲 2013/8/28
//
// 修改标识：
// 修改描述：
//
//----------------------------------------------------------------*/


(function ($) {

    function ajaxFileSuccess(result, callback, failCallback, exceptionCallback) {
        //返回Status100时，回调函数（返回成功
        var callback = callback;
        //返回Status300时，回调函数（返回错误）
        var failCallback = failCallback;
        //返回Status500.600时，回调函数（返回异常，平台异常）
        var exceptionCallback = exceptionCallback;

        //登陆超时
        if (result.Status == 100) {
            jqAlert(BuildExceptionMessage(result), function () { location.href = "/login.aspx"; });
            return;
        }

        if (result.Status == 200) {
            //成功
            if (!isNullOrEmpty(callback)) {
                if (result === null) {
                    callback(null);
                    return;
                }
                var contentType = $.type(result.Content);
                if (contentType === "undefined" || contentType === "null") {
                    callback(result);
                }
                else {
                    callback(result.Content);
                }
            }
        }
        else if (result.Status == 300) {
            //失败
            var msg = result.StateDescription;
            if (!isNullOrEmpty(failCallback)) {
                jqAlert(msg, function () { failCallback(result.Content); });
            }
            else {
                jqAlert(msg);
            }
        }
        else if (result.Status == 500) {
            //代码异常
            var title = "服务器错误：<br />日志ID：" + result.LogID + "<br />";
            var message = title + result.StateDescription;

            if (!isNullOrEmpty(exceptionCallback)) {
                jqAlert(message, function () { exceptionCallback(result.Content); });
            }
            else {
                jqAlert(message);
            }
        }
        else if (result.Status == 600) {
            //平台异常
            var msg = BuildExceptionMessage(result);

            if (!isNullOrEmpty(exceptionCallback)) {
                jqAlert(msg, function () { exceptionCallback(result.Content); });
            }
            else {
                jqAlert(msg);
            }
        }


    }


    jQuery.FileUpload = function (settings) {
        if (settings.url != "" && settings.url != null) {
            settings = jQuery.extend({

                secureuri: false,
                //  fileElementId: 'fileToUpload',
                dataType: 'json',
                success: function (data, status) {
                    this;
                },
                error: function (data, status, e) {
                    this;
                }
            }, settings);
        } else {
            jqAlert('请指定URL');
            return;
        }
        $.ajaxFileUpload({

            // url: '/Server/ProductionControl/Factory/PreAscend.aspx?Action=Import',
            url: settings.url,
            secureuri: false,
            fileElementId: settings.fileElementId,
            dataType: 'json',
            data: settings.data,
            success: function (data, status) {
                var result = data;
                ajaxFileSuccess(result, settings.successCallback, settings.failCallback, settings.exceptionCallback);
            },
            error: function (data, status, e) {
                var message = e && e.message ? e.message : e;
                if (!isNullOrEmpty(settings.exceptionCallback)) {
                    jqAlert(message, function () { settings.exceptionCallback(); });
                }
                else {
                    jqAlert(message);
                }
                //jqAlert(e);

            }
        })
    }
})(jQuery);



function DownloadTemplateCommon(TemplateName) {
    window.location.href = '/Server/Common.aspx?Action=DownLoadTemplate&TemplateName=' + TemplateName + ".xls";
    //        var url = "/Common/DownloadTemplate.aspx?method=DownLoadTemplate&TemplateName=" + TemplateName;
    //        $.ajax({
    //            type: "POST",
    //            url: url,

    //            datatype: "json",
    //            cache: false,
    //            async: false, //提交表单时锁住浏览器防止页面关闭中断事务
    //            success: function(data) {
    //                var Data = eval(unescape(data));
    //                if (Data[0].Status > 0) {
    //                    //  window.open(Data[0].Content);
    //                    window.location.href = '/Common/ExportServer.aspx?method=DownLoadFile&filePath=' + Data[0].Content;
    //                }
    //                else {
    //                    jqAlert_CB(Data[0].Content + "模版不存在", function() { });
    //                }
    //            },
    //            error: function(httpRequest, textStatus, errorThrown) {
    //                var strErrMsg = "意外出错，请刷新页面重试或联系技术支持人员!<br/> &nbsp;&nbsp;&nbsp;&nbsp;";
    //                jqAlert(strErrMsg);
    //            }
    //        });
    //  window.open("//Template//" + TemplateName);
}



function ImportDialog(strUrl) {
    var dialogID = "ImportDiv";
    var buttons = [
                {
                    ID: "ConfirmID",
                    text: "确定",
                    click: function () {
                        UploadFileLock(strUrl, "", "fileToUpload", dialogID, function (flag, data) {
                            var result = data;
                            jqAlert(data);
                            CloseDiv();

                        }, buttons, function (flag, data) {

                            var result = data
                            //CancelUIControl();
                            CloseDiv();
                            UploadCallback(result);
                        });
                    }
                },
                {
                    ID: "CancelID",
                    text: "取消",
                    click: function () {
                        $(this).dialog('close');
                        //  CancelUIControl();
                    }
                }
            ];

    jqDialog(dialogID, '导入', 400, 250, function () { }, buttons);
//    $('#ImportDiv').dialog({
//        close: CancelUIControl
//    });

}


//function ConfirmUIControl() {
//    $("#divControl").hide();
//    $("#divLoad").show();
//    $("#ConfirmID").button("disable")

//    $("#CancelID").button("disable");
//    dlBtnEnable(true);
//}

//function CancelUIControl() {
//    $("#divLoad").hide();
//    $("#divControl").show();
//    $("#ConfirmID").button("enable")
//    $("#CancelID").button("enable");
//    $("#ImportDiv").data("_Dialog_CanClose", true);
//    
//}

function lockBtn(btnEvents, isLock) {
    var btnObj = null;
    if (!isNullOrEmpty(btnEvents) && $.isArray(btnEvents)) {
        $.each(btnEvents, function (index, value) {
            var btnEvent = value;
            //ie and firefox
//            if ($.browser.msie || $.browser.mozilla) btnObj = $(btnEvent.target);
            //            else btnObj = $(btnEvent.currentTarget); //chrome
            btnObj = $("#" + btnEvent.ID);
            if (isLock)
                btnObj.button('disable'); //禁用按钮
            else
                btnObj.button('enable'); //禁用按钮 
        });
    }
}

function lockDialog(dialogId, flag) {
    
    $("#" + dialogId).data("_Dialog_CanClose", !flag);
}
function UploadFileLock(strUrl, htmlFormId, fileElementID, DialogId, Callback, btnEvents, onFailCallBack, onExceptionCallBack) {

//    $.FileUpload({
//        // url: '/Server/ProductionControl/Factory/PreAscend.aspx?Action=Import',
//        url: strUrl,
//        secureuri: false,
//        fileElementId: fileElementID,
//        dataType: 'json',
//        //data: vPostData,
//        type: 'post',
//        successCallback: function (data, status) {

//            if (Callback != null && $.type(Callback) == "function") {
//                Callback(true, data);
//            }

//        },
//        failCallback: function (data, status, e) {

//            if (onFailCallBack != null && $.type(onFailCallBack) == "function") {
//                onFailCallBack(false, data);
//            }
//        },
//        exceptionCallback: function (data, status, e) {

//            if (onExceptionCallBack != null && $.type(onExceptionCallBack) == "function") {
//                onExceptionCallBack(false, data);
//            }
//        }
//    })

    var fileElementID = fileElementID;
    var processDivId = "processDivId" + new Date().getTime();
   

    var vPostData;
    if (htmlFormId != null && htmlFormId != '') {
        if (!EasyUiValidate(htmlFormId))
            return;
        vPostData = getPostBodyToJson(htmlFormId);
        if ($.type(vPostData) == "string") {
            if (vPostData == "nodata")
                return;
        }
    }
//    var fileValue = $("#"+fileElementID).attr("value");
//    if (fileValue == null || fileValue == "") {
//        jqAlert("请选择上传的文件！");
//        return;
//    }
    //按钮锁定
    ConfirmUIControl(fileElementID, processDivId,DialogId,btnEvents);
   


    //回调函数前接触锁定
    var successCallBack = function (flag, data) {
        CancelUIControl(fileElementID, processDivId, DialogId, btnEvents);
        if (!isNullOrEmpty(Callback) && $.type(Callback) == "function") { Callback(flag, data); } 
     }
    var failCallBack = function (flag, data) {
        CancelUIControl(fileElementID, processDivId, DialogId, btnEvents);
        if (!isNullOrEmpty(onFailCallBack) && $.type(onFailCallBack) == "function") { onFailCallBack(flag, data); } 
    }
    var exceptionCallBack = function (flag, data) {
        CancelUIControl(fileElementID, processDivId, DialogId, btnEvents);
        if (!isNullOrEmpty(onExceptionCallBack) && $.type(onExceptionCallBack) == "function") { onExceptionCallBack(flag, data); }
    }
    UploadFile(strUrl, vPostData, fileElementID, successCallBack, failCallBack, exceptionCallBack);

   

}


function ConfirmUIControl(fileElementID, processId,DialogId, btnEvents) {
    
    var fileElement = $("#" + fileElementID);
    var fileElementValue = fileElement.attr("value") != null ? fileElement.attr("value") : "";
    var displayValue = "正在上传：" + fileElementValue.match(/[^\\]+\.[^\(]+/i); ;
    var divLoad = jQuery('<div id="' + processId + '">' +
                                 '<img style="width:16px;height:16px;float:left;margin-right:3px;" src="/Images/spinner-mini.gif" /> ' +
                                 '<div style="width:' + fileElement.outerWidth() + 'px;height:16px;float:left;text-overflow:ellipsis; white-space:nowrap; -o-text-overflow:ellipsis; overflow:hidden; " >' + displayValue + '</div>' +
                         '</div>');
    fileElement.after(divLoad);
    fileElement.toggle(false);

    lockBtn(btnEvents, true);
    lockDialog(DialogId, true);
}

function CancelUIControl(fileElementID, processId, DialogId, btnEvents) {

    $("#" + fileElementID).toggle(true);
    $("#" + processId).remove();
    lockBtn(btnEvents, false);
    lockDialog(DialogId, false);
 
 

}

function UploadFile(strUrl,vPostData, fileElementID, Callback, onFailCallBack, onExceptionCallBack) {
   
    $.FileUpload({
        // url: '/Server/ProductionControl/Factory/PreAscend.aspx?Action=Import',
        url: strUrl,
        secureuri: false,
        fileElementId: fileElementID,
        dataType: 'json',
        data: vPostData,
        type: 'post', 
        successCallback: function (data, status) {
            
            if (Callback != null && $.type(Callback) == "function") {
                Callback(true, data);
            }

        },
        failCallback: function (data, status, e) {
            
            if (onFailCallBack != null && $.type(onFailCallBack) == "function") {
                onFailCallBack(false, data);
            }
        },
        exceptionCallback: function (data, status, e) {
          
            if (onExceptionCallBack != null && $.type(onExceptionCallBack) == "function") {
                onExceptionCallBack(false, data);
            }
        }
    })

}

function UploadCallback(result) {
    window.location.href = "/Server/Common.aspx?Action=DownLoadFile&FilePath=" + result;
    //$("#ImportDiv").dialog('close');
}

//公告附件下载
function DownloadAnnounceAttach(result) {
    window.location.href = "/Server/Common.aspx?Action=DownloadAnnounceAttach&FilePath=" + result;
}


function ExportFile(strUrl, formId) {
    submitJSONForm(strUrl, formId, function (data) {
        
            var result = data;
            window.location.href = "/Server/Common.aspx?Action=DownLoadFile&FilePath=" + result;
        
    });
}

function CloseDiv() {
    $("#ImportDiv").data("_Dialog_CanClose", true);
    $("#ImportDiv").dialog('close');
}
function dlBtnEnable(enable) {
    var dlgButton = $('#ui-dialog-buttonpane button'); //喔喔,全选所有dialog的按钮,你也可以加些条件,选定指定窗口,不过我这里没必要.
    if (enable) {
        dlgButton.attr('disabled', '');
        dlgButton.removeClass('ui-state-disabled');
    } else {
        dlgButton.attr('disabled', 'disabled');
        dlgButton.addClass('ui-state-disabled');
    }
}